<?php
/**
 * Created by jinqiang on 2025/3/20 14:06.
 * Copyright (c) 2025, Your Company. All rights reserved.
 */


namespace App\Http\Services\Banshi;


use App\Http\Models\Mysql\BrandTable;
use App\Http\Models\Mysql\CategoryTable;
use App\Http\Models\Mysql\ColourTable;
use App\Http\Models\Mysql\MaterielCategoryTable;
use App\Http\Models\Mysql\MaterielTable;
use App\Http\Models\Mysql\Number4Table;
use App\Http\Models\Mysql\PriceTypeTable;
use App\Http\Models\Mysql\ProductCategoryTable;
use App\Http\Models\Mysql\SampleProcessesTable;
use App\Http\Models\Mysql\SeasonTable;
use App\Http\Models\Mysql\StyleSampleProcessesTable;
use App\Http\Models\Mysql\StyleT4Table;
use App\Http\Models\Mysql\StyleT68Table;
use App\Http\Models\Mysql\StyleTable;
use App\Http\Models\Mysql\T17Table;
use App\Http\Models\Mysql\T1Table;
use App\Http\Models\Mysql\T4Table;
use App\Http\Models\Mysql\T68Table;
use App\Http\Models\Mysql\T73Table;
use App\Http\Models\Mysql\TargetTable;
use App\Http\Models\Mysql\TypeTable;
use App\Http\Models\Mysql\UnitTable;
use App\Http\Models\Mysql\VerifyPriceItemTable;
use App\Http\Models\Mysql\VerifyPriceTable;
use App\Http\Repository\CommonRepository;
use Illuminate\Support\Facades\DB;

class InformationService
{
    public function targetSearch($param)
    {
        $conn = (new TargetTable());
        if($param['name'] ?? ""){
            $conn = $conn->where('name', 'like', '%'.$param['name'].'%');
        }
        $res = $conn->orderBy('id', 'asc')->paginate((Int)$param['limit'])->toArray();
        return [
            'data' => $res['data'],
            'total' => $res['total']
        ];
    }

    public function targetSave($param)
    {
        $data = [
            'number' => $param['number'],
            'name' => $param['name'],
            'sex' => 0,
            'begin_age' => (Int)$param['begin_age'],
            'end_age' => (Int)$param['end_age']
        ];
        if($param['id'] ?? ""){
            $exist = (new TargetTable())->where('id', '<>', (Int)$param['id'])->where(function($query) use($param){
                $query->where('number', $param['number'])
                    ->orWhere('name', $param['name']);
            })->exists();
            if($exist){
                return ['code' => -1, 'msg' => '操作失败：目标用户编码、名称已存在'];
            }
            return (new TargetTable())->updateData((Int)$param['id'], $data);
        }else{
            $exist = (new TargetTable())->where(function($query) use($param){
                $query->where('number', $param['number'])
                    ->orWhere('name', $param['name']);
            })->exists();
            if($exist){
                return ['code' => -1, 'msg' => '操作失败：目标用户编码、名称已存在'];
            }
            return (new TargetTable())->createData($data);
        }
    }

    public function seasonSearch($param)
    {
        $conn = (new SeasonTable());
        if($param['name'] ?? ""){
            $conn = $conn->where('name', 'like', '%'.$param['name'].'%');
        }
        $res = $conn->orderBy('id', 'asc')->paginate((Int)$param['limit'])->toArray();
        return [
            'data' => $res['data'],
            'total' => $res['total']
        ];
    }

    public function seasonSave($param)
    {
        $data = [
            'number' => $param['number'],
            'name' => $param['name'],
        ];
        if($param['id'] ?? ""){
            $exist = (new SeasonTable())->where('id', '<>', (Int)$param['id'])->where(function($query) use($param){
                $query->where('number', $param['number'])
                    ->orWhere('name', $param['name']);
            })->exists();
            if($exist){
                return ['code' => -1, 'msg' => '操作失败：编码、名称已存在'];
            }
            return (new SeasonTable())->updateData((Int)$param['id'], $data);
        }else{
            $exist = (new SeasonTable())->where(function($query) use($param){
                $query->where('number', $param['number'])
                    ->orWhere('name', $param['name']);
            })->exists();
            if($exist){
                return ['code' => -1, 'msg' => '操作失败：编码、名称已存在'];
            }
            return (new SeasonTable())->createData($data);
        }
    }

    public function brandSearch($param)
    {
        $conn = (new BrandTable());
        if($param['name'] ?? ""){
            $conn = $conn->where('name', 'like', '%'.$param['name'].'%');
        }
        $res = $conn->orderBy('id', 'asc')->paginate((Int)$param['limit'])->toArray();
        return [
            'data' => $res['data'],
            'total' => $res['total']
        ];
    }

    public function brandSave($param)
    {
        $data = [
            'number' => $param['number'],
            'name' => $param['name'],
        ];
        if($param['id'] ?? ""){
            $exist = (new BrandTable())->where('id', '<>', (Int)$param['id'])->where(function($query) use($param){
                $query->where('number', $param['number'])
                    ->orWhere('name', $param['name']);
            })->exists();
            if($exist){
                return ['code' => -1, 'msg' => '操作失败：编码、名称已存在'];
            }
            return (new BrandTable())->updateData((Int)$param['id'], $data);
        }else{
            $exist = (new BrandTable())->where(function($query) use($param){
                $query->where('number', $param['number'])
                    ->orWhere('name', $param['name']);
            })->exists();
            if($exist){
                return ['code' => -1, 'msg' => '操作失败：编码、名称已存在'];
            }
            return (new BrandTable())->createData($data);
        }
    }

    public function colourSearch($param)
    {
        $conn = (new ColourTable());
        if($param['name'] ?? ""){
            $conn = $conn->where('name', 'like', '%'.$param['name'].'%');
        }
        if(isset($param['state']) && $param['state'] != ""){
            $conn = $conn->where('state', (Int)$param['state']);
        }
        $res = $conn->orderBy('id', 'asc')->paginate((Int)$param['limit'])->toArray();
        foreach($res['data'] as &$item){
            $item['value_ch'] = CommonRepository::getColor($item['value']);
        }
        unset($item);
        return [
            'data' => $res['data'],
            'total' => $res['total']
        ];
    }

    public function coloreStateSet($id, $state)
    {
        return (new ColourTable())->updateData($id, ['state' => $state]);
    }

    public function colourSave($param)
    {
        $data = [
            'number' => $param['number'] ?: "",
            'name' => $param['name'],
            'value' => empty($param['value_ch']) ? 0 : CommonRepository::setColor($param['value_ch']),
            'state' => (Int)$param['state']
        ];
        if($param['id'] ?? ""){
            $exist = (new ColourTable())->where('id', '<>', (Int)$param['id'])->where('number', $param['number'])->exists();
            if($exist){
                return ['code' => -1, 'msg' => '操作失败：编码已存在'];
            }
            return (new ColourTable())->updateData((Int)$param['id'], $data);
        }else{
            $exist = (new ColourTable())->where('number', $param['number'])->exists();
            if($exist){
                return ['code' => -1, 'msg' => '操作失败：编码已存在'];
            }
            return (new ColourTable())->createData($data);
        }
    }

    public function classSearch($param)
    {
        $conn = (new ProductCategoryTable());
        if($param['name'] ?? ""){
            $conn = $conn->where('name', 'like', '%'.$param['name'].'%');
        }
        $res = $conn->orderBy('position', 'asc')->paginate((Int)$param['limit'])->toArray();
        return [
            'data' => $res['data'],
            'total' => $res['total']
        ];
    }

    public function classSave($param)
    {
        $data = [
            'number' => $param['number'] ?: "",
            'name' => $param['name'],
        ];
        if($param['id'] ?? ""){
            $exist = (new ProductCategoryTable())->where('id', '<>', (Int)$param['id'])->where('number', $param['number'])->exists();
            if($exist){
                return ['code' => -1, 'msg' => '操作失败：编码已存在'];
            }
            return (new ProductCategoryTable())->updateData((Int)$param['id'], $data);
        }else{
            $exist = (new ProductCategoryTable())->where('number', $param['number'])->exists();
            if($exist){
                return ['code' => -1, 'msg' => '操作失败：编码已存在'];
            }
            $lastObj = (new ProductCategoryTable())->orderBy('position', 'desc')->first(['position'])->toArray();
            $data['position'] = $lastObj['position']+ 1;
            return (new ProductCategoryTable())->createData($data);
        }
    }

    public function categorySearch($param)
    {
        $conn = (new CategoryTable())->where('product_category_id', (Int)$param['tab']);
        $res = $conn->orderBy('id', 'asc')->paginate((Int)$param['limit'])->toArray();
        return [
            'data' => $res['data'],
            'total' => $res['total']
        ];
    }

    public function categorySave($param)
    {
        $data = [
            'product_category_id' => (Int)$param['product_category_id'],
            'pid' => (Int)$param['pid'],
            'number' => $param['number'],
            'name' => $param['name'],
        ];
        if($param['id'] ?? ""){
            $exist = (new CategoryTable())->where('id', '<>', (Int)$param['id'])->where('product_category_id', $data['product_category_id'])
                ->where(function($query) use($param){
                    $query->where('number', $param['number'])
                        ->orWhere('name', $param['name']);
                })->exists();
            if($exist){
                return ['code' => -1, 'msg' => '操作失败：编码、名称已存在'];
            }
            return (new CategoryTable())->updateData((Int)$param['id'], $data);
        }else{
            $exist = (new CategoryTable())->where('product_category_id', $data['product_category_id'])->where(function($query) use($param){
                $query->where('number', $param['number'])
                    ->orWhere('name', $param['name']);
            })->exists();
            if($exist){
                return ['code' => -1, 'msg' => '操作失败：编码、名称已存在'];
            }
            return (new CategoryTable())->createData($data);
        }
    }

    public function categoryDel($id)
    {
        $exists = (new StyleTable())->where('detail_category_id', $id)->exists();
        if($exists){
            return ['code' => -1, 'msg' => '删除失败：该设计分类已被依赖'];
        }
        return (new CategoryTable())->deleteData($id);
    }

    public function typeSearch($param)
    {
        $conn = (new TypeTable());
        if($param['name'] ?? ""){
            $conn = $conn->where('name', 'like', '%'.$param['name'].'%');
        }
        $res = $conn->orderBy('id', 'asc')->paginate((Int)$param['limit'])->toArray();
        return [
            'data' => $res['data'],
            'total' => $res['total']
        ];
    }

    public function typeSave($param)
    {
        $data = [
            'number' => $param['number'],
            'name' => $param['name'],
        ];
        if($param['id'] ?? ""){
            $exist = (new TypeTable())->where('id', '<>', (Int)$param['id'])->where(function($query) use($param){
                $query->where('number', $param['number'])
                    ->orWhere('name', $param['name']);
            })->exists();
            if($exist){
                return ['code' => -1, 'msg' => '操作失败：编码、名称已存在'];
            }
            return (new TypeTable())->updateData((Int)$param['id'], $data);
        }else{
            $exist = (new TypeTable())->where(function($query) use($param){
                $query->where('number', $param['number'])
                    ->orWhere('name', $param['name']);
            })->exists();
            if($exist){
                return ['code' => -1, 'msg' => '操作失败：编码、名称已存在'];
            }
            return (new TypeTable())->createData($data);
        }
    }

    public function cultureSearch($param)
    {
        $conn = (new T1Table());
        if($param['name'] ?? ""){
            $conn = $conn->where('name', 'like', '%'.$param['name'].'%');
        }
        $res = $conn->orderBy('id', 'asc')->paginate((Int)$param['limit'])->toArray();
        return [
            'data' => $res['data'],
            'total' => $res['total']
        ];
    }

    public function cultureSave($param)
    {
        $data = [
            'number' => $param['number'],
            'name' => $param['name'],
        ];
        if($param['id'] ?? ""){
            $exist = (new T1Table())->where('id', '<>', (Int)$param['id'])->where(function($query) use($param){
                $query->where('number', $param['number'])
                    ->orWhere('name', $param['name']);
            })->exists();
            if($exist){
                return ['code' => -1, 'msg' => '操作失败：编码、名称已存在'];
            }
            return (new T1Table())->updateData((Int)$param['id'], $data);
        }else{
            $exist = (new T1Table())->where(function($query) use($param){
                $query->where('number', $param['number'])
                    ->orWhere('name', $param['name']);
            })->exists();
            if($exist){
                return ['code' => -1, 'msg' => '操作失败：编码、名称已存在'];
            }
            return (new T1Table())->createData($data);
        }
    }

    public function goodsSearch($param)
    {
        $conn = (new T4Table());
        if($param['name'] ?? ""){
            $conn = $conn->where('name', 'like', '%'.$param['name'].'%');
        }
        $res = $conn->orderBy('id', 'asc')->paginate((Int)$param['limit'])->toArray();
        return [
            'data' => $res['data'],
            'total' => $res['total']
        ];
    }

    public function goodsSave($param)
    {
        $data = [
            'name' => $param['name'],
        ];
        if($param['id'] ?? ""){
            $exist = (new T4Table())->where('id', '<>', (Int)$param['id'])->where('name', $param['name'])->exists();
            if($exist){
                return ['code' => -1, 'msg' => '操作失败：名称已存在'];
            }
            return (new T4Table())->updateData((Int)$param['id'], $data);
        }else{
            $exist = (new T4Table())->where('name', $param['name'])->exists();
            if($exist){
                return ['code' => -1, 'msg' => '操作失败：名称已存在'];
            }
            return (new T4Table())->createData($data);
        }
    }

    public function goodsDel($id)
    {
        $exists = (new StyleT4Table())->where('t4_id', $id)->exists();
        if($exists){
            return ['code' => -1, 'msg' => '删除失败：该商品属性已被依赖'];
        }
        return (new T4Table())->deleteData($id);
    }

    public function suitSearch($param)
    {
        $conn = (new T17Table());
        if($param['number'] ?? ""){
            $conn = $conn->where('number', 'like', $param['number']."%");
        }
        if($param['name'] ?? ""){
            $conn = $conn->where('name', 'like', '%'.$param['name'].'%');
        }
        $res = $conn->orderBy('id', 'desc')->paginate((Int)$param['limit'])->toArray();
        return [
            'data' => $res['data'],
            'total' => $res['total']
        ];
    }

    public function suitSave($param)
    {
        if($param['id'] ?? ""){
            $exist = (new T17Table())->where('id', '<>', (Int)$param['id'])->where('name', $param['name'])->exists();
            if($exist){
                return ['code' => -1, 'msg' => '操作失败：套装名称已存在'];
            }
            return (new T17Table())->updateData((Int)$param['id'], ['name' => $param['name']]);
        }else{
            $exist = (new T17Table())->where('name', $param['name'])->exists();
            if($exist){
                return ['code' => -1, 'msg' => '操作失败：名称已存在'];
            }
            $number4 = (new Number4Table())->first();
            $number4Data = ['head' => date('y'), 'count' => $number4->head == date('y') ? $number4->count + 1 : 1];
            DB::connection("mysql_sj")->table("number_4")->update($number4Data);
            $data = [
                'number' => $number4Data['head'].str_pad($number4Data['count'],4,"0",STR_PAD_LEFT),
                'name' => $param['name']
            ];
            return (new T17Table())->createData($data);
        }
    }

    public function suitDel($id)
    {
        $exists = (new StyleTable())->where('t17_id', $id)->exists();
        if($exists){
            return ['code' => -1, 'msg' => '删除失败：该套装编号已被依赖'];
        }
        return (new T17Table())->deleteData($id);
    }

    public function ptypeSearch($param)
    {
        $conn = (new PriceTypeTable());
        if($param['name'] ?? ""){
            $conn = $conn->where('name', 'like', '%'.$param['name'].'%');
        }
        $res = $conn->orderBy('id', 'asc')->paginate((Int)$param['limit'])->toArray();
        return [
            'data' => $res['data'],
            'total' => $res['total']
        ];
    }

    public function ptypeSave($param)
    {
        if($param['id'] ?? ""){
            $exist = (new PriceTypeTable())->where('id', '<>', (Int)$param['id'])->where('name', $param['name'])->exists();
            if($exist){
                return ['code' => -1, 'msg' => '操作失败：套装名称已存在'];
            }
            return (new PriceTypeTable())->updateData((Int)$param['id'], ['name' => $param['name']]);
        }else{
            $exist = (new PriceTypeTable())->where('name', $param['name'])->exists();
            if($exist){
                return ['code' => -1, 'msg' => '操作失败：名称已存在'];
            }
            return (new PriceTypeTable())->createData(['name' => $param['name']]);
        }
    }

    public function ptypeDel($id)
    {
        $exists = (new VerifyPriceItemTable())->where('price_type_id', $id)->exists();
        if($exists){
            return ['code' => -1, 'msg' => '删除失败：该核价类型已被依赖'];
        }
        return (new PriceTypeTable())->deleteData($id);
    }

    public function puseSearch($param)
    {
        $conn = (new T73Table());
        if($param['name'] ?? ""){
            $conn = $conn->where('name', 'like', '%'.$param['name'].'%');
        }
        $res = $conn->orderBy('id', 'asc')->paginate((Int)$param['limit'])->toArray();
        return [
            'data' => $res['data'],
            'total' => $res['total']
        ];
    }

    public function puseSave($param)
    {
        if($param['id'] ?? ""){
            $exist = (new T73Table())->where('id', '<>', (Int)$param['id'])->where('name', $param['name'])->exists();
            if($exist){
                return ['code' => -1, 'msg' => '操作失败：套装名称已存在'];
            }
            return (new T73Table())->updateData((Int)$param['id'], ['name' => $param['name']]);
        }else{
            $exist = (new T73Table())->where('name', $param['name'])->exists();
            if($exist){
                return ['code' => -1, 'msg' => '操作失败：名称已存在'];
            }
            return (new T73Table())->createData(['name' => $param['name']]);
        }
    }

    public function puseDel($id)
    {
        $exists = (new VerifyPriceTable())->where('t73_id', $id)->exists();
        if($exists){
            return ['code' => -1, 'msg' => '删除失败：该核价类型已被依赖'];
        }
        return (new T73Table())->deleteData($id);
    }

    public function artsSearch($param)
    {
        $conn = (new T68Table());
        if($param['name'] ?? ""){
            $conn = $conn->where('name', 'like', '%'.$param['name'].'%');
        }
        $res = $conn->orderBy('id', 'asc')->paginate((Int)$param['limit'])->toArray();
        return [
            'data' => $res['data'],
            'total' => $res['total']
        ];
    }

    public function artsSave($param)
    {
        if($param['id'] ?? ""){
            $exist = (new T68Table())->where('id', '<>', (Int)$param['id'])->where('name', $param['name'])->exists();
            if($exist){
                return ['code' => -1, 'msg' => '操作失败：套装名称已存在'];
            }
            return (new T68Table())->updateData((Int)$param['id'], ['name' => $param['name']]);
        }else{
            $exist = (new T68Table())->where('name', $param['name'])->exists();
            if($exist){
                return ['code' => -1, 'msg' => '操作失败：名称已存在'];
            }
            return (new T68Table())->createData(['name' => $param['name']]);
        }
    }

    public function artsDel($id)
    {
        $exists = (new StyleT68Table())->where('t68_id', $id)->exists();
        if($exists){
            return ['code' => -1, 'msg' => '删除失败：该工艺类型已被依赖'];
        }
        return (new T68Table())->deleteData($id);
    }

    public function sampleSearch($param)
    {
        $conn = (new SampleProcessesTable());
        if($param['name'] ?? ""){
            $conn = $conn->where('name', 'like', '%'.$param['name'].'%');
        }
        $res = $conn->orderBy('id', 'asc')->paginate((Int)$param['limit'])->toArray();
        return [
            'data' => $res['data'],
            'total' => $res['total']
        ];
    }

    public function sampleSave($param)
    {
        $data = [
            'name' => $param['name'],
            'number' => $param['number']
        ];
        if($param['id'] ?? ""){
            $exist = (new SampleProcessesTable())->where('id', '<>', (Int)$param['id'])->where(function($query) use($param){
                $query->where('number', $param['number'])
                    ->orWhere('name', $param['name']);
            })->exists();
            if($exist){
                return ['code' => -1, 'msg' => '操作失败：编码、名称已存在'];
            }
            return (new SampleProcessesTable())->updateData((Int)$param['id'], $data);
        }else{
            $exist = (new SampleProcessesTable())->where(function($query) use($param){
                    $query->where('number', $param['number'])
                        ->orWhere('name', $param['name']);
                })->exists();
            if($exist){
                return ['code' => -1, 'msg' => '操作失败：编码、名称已存在'];
            }
            return (new SampleProcessesTable())->createData($data);
        }
    }

    public function sampleDel($id)
    {
        $exists = (new StyleSampleProcessesTable())->where('sample_processes_id', $id)->exists();
        if($exists){
            return ['code' => -1, 'msg' => '删除失败：该样衣工序已被依赖'];
        }
        return (new SampleProcessesTable())->deleteData($id);
    }

    public function munitSearch($param)
    {
        $conn = (new UnitTable());
        if($param['name'] ?? ""){
            $conn = $conn->where('name', 'like', '%'.$param['name'].'%');
        }
        $res = $conn->orderBy('id', 'desc')->paginate((Int)$param['limit'])->toArray();
        return [
            'data' => $res['data'],
            'total' => $res['total']
        ];
    }

    public function munitSave($param)
    {
        $data = [
            'name' => $param['name']
        ];
        if($param['id'] ?? ""){
            $exist = (new UnitTable())->where('id', '<>', (Int)$param['id'])->where('name', $param['name'])->exists();
            if($exist){
                return ['code' => -1, 'msg' => '操作失败：名称已存在'];
            }
            return (new UnitTable())->updateData((Int)$param['id'], $data);
        }else{
            $exist = (new UnitTable())->where('name', $param['name'])->exists();
            if($exist){
                return ['code' => -1, 'msg' => '操作失败：名称已存在'];
            }
            return (new UnitTable())->createData($data);
        }
    }

    public function munitDel($id)
    {
        $exists = (new MaterielTable())->where('materiel_major_unit_id', $id)
            ->orWhere('materiel_minor_unit_id', $id)->exists();
        if($exists){
            return ['code' => -1, 'msg' => '删除失败：该物料单位已被依赖'];
        }
        return (new UnitTable())->deleteData($id);
    }

    public function mcategorySearch($param)
    {
        $conn = (new MaterielCategoryTable())->where('pid', 0);
        if($param['name'] ?? ""){
            $conn = $conn->where('name', 'like', '%'.$param['name'].'%');
        }
        if($param['tab'] ?? ""){
            $conn = $conn->where('materiel_major_category_id', (Int)$param['tab']);
        }
        $res = $conn->orderBy('id', 'asc')->paginate((Int)$param['limit'])->toArray();
        $pids = array_column($res['data'], "id");
        $children = (new MaterielCategoryTable())->whereIn('pid', $pids)->get()->toArray();
        foreach ($res['data'] as &$item){
            $item['p_name'] = "根目录";
            foreach ($children as $child){
                if($child['pid'] == $item['id']){
                    $child['p_name'] = $item['name'];
                    $item['children'][] = $child;
                }
            }
        }
        unset($item);
        return [
            'data' => $res['data'],
            'total' => $res['total']
        ];
    }

    public function mcategorySave($param)
    {
        $data = [
            'pid' => (Int)$param['pid'],
            'name' => $param['name'],
            'materiel_major_category_id' => (Int)$param['materiel_major_category_id'],
            'materiel_attribute_id' => (Int)$param['materiel_attribute_id']
        ];
        if($param['id'] ?? ""){
            $exist = (new MaterielCategoryTable())->where('id', '<>', (Int)$param['id'])->where('materiel_major_category_id', (Int)$param['materiel_major_category_id'])
                ->where('name', $param['name'])->exists();
            if($exist){
                return ['code' => -1, 'msg' => '操作失败：名称已存在'];
            }
            return (new MaterielCategoryTable())->updateData((Int)$param['id'], $data);
        }else{
            $exist = (new MaterielCategoryTable())->where('materiel_major_category_id', (Int)$param['materiel_major_category_id'])->where('name', $param['name'])->exists();
            if($exist){
                return ['code' => -1, 'msg' => '操作失败：名称已存在'];
            }
            return (new MaterielCategoryTable())->createData($data);
        }
    }

    public function mcategoryDel($id)
    {
        $exists = (new MaterielTable())->where('materiel_category_id', $id)->exists();
        if($exists){
            return ['code' => -1, 'msg' => '删除失败：该物料分类已被依赖'];
        }
        return (new MaterielCategoryTable())->deleteData($id);
    }
}
